/*
 * Copyright (C), 2002-2017, roy 学习代码
 * FileName: GenerTemplate.java
 * Author:   roy
 * Date:     2017年1月8日 下午4:16:15
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.roy.roycodegenerator.common.velocity.generator;

import java.io.File;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.roy.roycodegenerator.service.generator.dto.TableDto;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author roy
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class GenerTemplateTools {
    private static final Logger logger = LoggerFactory.getLogger(GenerTemplateTools.class);

    public static void generatorTemplate(TableDto tableDto, String templatePath, String generateFilePath,
            String encoding) {

        Map<String, Object> datas = GenerTemplateTools.initparams(tableDto);

        Context context = new VelocityContext(datas);

        VelocityEngine velocityEngine = new VelocityEngine();

        Properties properties = new Properties();
        // 模版路径
        properties.put(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templatePath);
        properties.setProperty(VelocityEngine.ENCODING_DEFAULT, encoding);
        properties.put(VelocityEngine.INPUT_ENCODING, encoding);
        properties.put(VelocityEngine.OUTPUT_ENCODING, encoding);
        try {
            velocityEngine.init(properties);
            File file = new File(templatePath);
            File[] templates = file.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    name = name.toLowerCase();
                    return name.endsWith(".java") || name.endsWith(".jsp") || name.endsWith(".xml")
                            || name.endsWith(".ftl");
                }
            });
            for (File template : templates) {
                String fileName = template.getName();
                org.apache.velocity.Template t = velocityEngine.getTemplate(fileName);
                String outFileName = fileName.replace("${model}", tableDto.getClassName());

                File outFile = new File(generateFilePath + outFileName);
                outFile.delete();
                outFile.createNewFile();

                PrintWriter dw = new PrintWriter(generateFilePath + outFileName, encoding);
                t.merge(context, dw);
                dw.close();
            }

        } catch (ResourceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseErrorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        logger.debug("生成结束");
    }

    private static Map<String, Object> initparams(TableDto tableDto) {
        Map<String, Object> datas = new HashMap<String, Object>();
        datas.put("model", tableDto.getClassName());
        datas.put("lowercasemodel", tableDto.getEntityParamName());

        datas.put("date", new Date());

        datas.put("basepackage", tableDto.getPackageBasePatch());
        
        //entity层需要的路径
        datas.put("dmopackage", tableDto.getPackageBasePatch() + ".entity."+tableDto.getNameSpace());
        datas.put("dmopackageClass", tableDto.getPackageBasePatch() + ".entity."+tableDto.getNameSpace()+"."+tableDto.getClassName()+"Entity");
        
        //dao层接口需要的路径
        datas.put("daopackage", tableDto.getPackageBasePatch() + ".dao."+tableDto.getNameSpace());
        datas.put("daopackageClass", tableDto.getPackageBasePatch() + ".dao."+tableDto.getNameSpace()+"."+tableDto.getClassName()+"Dao");
        datas.put("daopackageClassDesc",datas.get("daopackageClass")+"#");
        
        //dao层实现类需要的路径
        datas.put("daoimplpackage", datas.get("daopackage") + ".impl");
        datas.put("namespace", tableDto.getNameSpace());
        
        //service层类需要路径
        datas.put("servicepackage", tableDto.getPackageBasePatch() + ".service."+tableDto.getNameSpace());
        datas.put("servicepackageClass", tableDto.getPackageBasePatch() + ".service."+tableDto.getNameSpace()+"."+tableDto.getClassName()+"Service");
        datas.put("servicepackageClassDesc",datas.get("servicepackageClass")+"#");
        //dao层实现类需要的路径
        datas.put("serviceImplpackage", datas.get("servicepackage") + ".impl");
        
        
        
        datas.put("namespaceController", tableDto.getNameSpace().replace(".", "/"));

        datas.put("namespace", tableDto.getEntityParamName());

        datas.put("author", tableDto.getAuthor());
        datas.put("columns", tableDto.getColumns());
        datas.put("commonPackage", tableDto.getCommonPackage());
        return datas;
    }
}
